package com.engine.ld.optimize;

import com.weaver.general.BaseBean;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import weaver.conn.RecordSet;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ZhangLei
 * @date 2021/7/1
 */
public class Cgxx {

    private static final BaseBean bb = new BaseBean();

    public String doCgxx(String requestid){

//        new HashMap<>();
        String[] mainField = {"LIFNR","MATNR","INFNR","ESOKZ","VERKF","TELF1","MEINS","UMREN","UMREZ","URZLA","ZFLAG",
                "LOEKZ","EKORG","APLFZ","EKGRP","NORBM","MINBM","UEBTO","MWSKZ","WEBRE","NETPR","WAERS","PEINH",
                "BPRME","KSCHL","PRDAT","BPUMN","BPUMZ","EINELOEKZ","ZYXQBS","ZJTBS","DATAB","DATBI","KSTBM","KONMS",
                "KBETR","ZTJYW"};
//        LOEKZ1对应数据库字段为：LOEKZ
        String[] detailField = {"LIFNR","MATNR","INFNR","ZJTBS","DATAB","DATBI","KSTBM","KONMS","KBETR"};

//        mainMap存储主表的键值对数据
        Map<String,Object> mainMap = getData(mainField,requestid,"formtable_main_155");
//        detailMap存储明细表表的键值对数据
        Map<String,Object> detailMap = getData(detailField,requestid,"formtable_main_155");

//        组装xml
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        Document document = builder.newDocument();
        Element root = document.createElement("ROOT");
        document.appendChild(root);

        //        创建HEAD节点以及子节点，并赋值
        Element head = document.createElement("HEAD");
        for (String s : mainField) {
            if ("EINELOEKZ".equals(s)){
                appendChild(document,head,"LOEKZ1",mainMap.get(s).toString());
            }else if ("ZJTBS".equals(s)){
                appendChild(document,head,"ZJTBS","");
            } else {
                appendChild(document,head,s,mainMap.get(s).toString());
            }
        }
//        根据业务标识为HRAD节点下的ZCZTJ节点赋值
        if ("2".equals(mainMap.get("ZFLAG").toString())){
            appendChild(document,head,"ZCZTJ","X");
        }else {
            appendChild(document,head,"ZCZTJ","");
        }
        root.appendChild(head);

        //        创建ITEM节点以及子节点，并赋值
        Element item = document.createElement("ITEM");
        for (String s : mainField) {
            appendChild(document,item,s,detailMap.get(s).toString());
        }
        root.appendChild(item);
        bb.writeLog("传给SAP的参数是："+createXmlToString(document));
        return createXmlToString(document);
    }

    /**
     * @param fields 需要查询字段的String类型数组
     * @param requestid where条件
     * 实现查询并将结果存储到Map集合中
    * */
    private Map<String,Object> getData(String[] fields, String requestid,String tableName){
        Map<String,Object> dataMap = new HashMap<>();
        String mainsql = "select ";
        for (int i = 0; i < fields.length; i++) {
            if (i == fields.length-1){
                mainsql += fields[i]+" ";
            }else if ("ZJTBS".equals(fields[i])){
                mainsql += "";
            }else {
                mainsql += fields[i]+",";
            }
        }
        mainsql += "from "+tableName+" a where a.requestid="+requestid;

        RecordSet rsMain = new RecordSet();
        rsMain.executeQuery(mainsql);
        bb.writeLog("查询的sql是："+mainsql);
        while (rsMain.next()){
            bb.writeLog("尝试从搜索结果中获取数据");
            bb.writeLog(rsMain.getString("LIFNR"));
        }
        if (rsMain.next()){
            for (String field : fields) {
                dataMap.put(field,rsMain.getString(field));
            }
        }
        return dataMap;
    }


    /**
     * document对象中添加子项
     * @param document ducument对象
     * @param parent 父元素
     * @param key 元素标签
     * @param value 元素content值
     */
    private static void appendChild(Document document, Element parent, String key, String value) {
        Element child = document.createElement(key);
        if(child != null) {
            child.setTextContent(value);
        }
        parent.appendChild(child);
    }



    /**
     * 生成xml字符串
     * @param document Document树对象
     * @return 整个xml字符串
     */
    private static String createXmlToString(org.w3c.dom.Document document){
        String xmlString = null;
        try {
            // 创建TransformerFactory工厂对象
            TransformerFactory transFactory = TransformerFactory.newInstance();
            // 通过工厂对象, 创建Transformer对象
            Transformer transformer = transFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            //使Xml自动换行, 并自动缩进
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");  //中间的参数网址固定写法(这里还没搞懂)
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");                          //是否设置缩进（indent: yes|no）
            // 创建DOMSource对象并将Document加载到其中
            DOMSource domSource = new DOMSource(document);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // 使用Transformer的transform()方法将DOM树转换成XML
            transformer.transform(domSource, new StreamResult(bos));
            xmlString = bos.toString();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return xmlString;
    }
}
